package com.fastjrun.share.demo.service.impl;


import com.fastjrun.apiworld.vo.PageResult;
import com.fastjrun.share.demo.dao.LogRecordDao;
import com.fastjrun.share.demo.dto.LogRecordQueryDTO;
import com.fastjrun.share.demo.entity.LogRecord;
import com.fastjrun.share.demo.entity.LogRecordExample;
import com.fastjrun.share.demo.helper.EntityToVOConverter;
import com.fastjrun.share.demo.service.BaseDemoService;
import com.fastjrun.share.demo.service.LogRecordManagerService;
import com.fastjrun.share.demo.vo.LogRecordVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 注意：本内容仅限于公司内部传阅，禁止外泄以及用于其他的商业目的
 *
 * @author cuiyingfeng @Copyright 2021 快嘉. All rights reserved.
 */
@Service("logRecordManagerService")
public class LogRecordManagerServiceImpl extends BaseDemoService
    implements LogRecordManagerService {
  @Resource LogRecordDao logRecordDao;

  @Override
  public PageResult<LogRecordVO> search(LogRecordQueryDTO requestBody) {
    PageResult<LogRecordVO> response = new PageResult();
    List<LogRecordVO> list;

    Long userId = requestBody.getUserId();
    String mobile = requestBody.getMobile();
    String userName = requestBody.getUsername();
    String email = requestBody.getEmail();
    Integer current = requestBody.getCurrent();
    Integer size = requestBody.getSize();

    LogRecordExample logRecordExample = new LogRecordExample();
    LogRecordExample.Criteria criteria = logRecordExample.createCriteria();

    if(current==null){
      current=PAGE_CURRENT;
    }
    if(size==null){
      size=PAGE_SIZE;
    }

    if (userId != null) {
      criteria.andUserIdEqualTo(userId);
    }

    if (mobile != null && !mobile.equals("")) {
      if (criteria.getCriteria().size() > 0) {
        logRecordExample.or().andMobileEqualTo(mobile);
      }else{
        criteria.andMobileEqualTo(mobile);
      }

    }

    if (userName != null && !userName.equals("")) {
      if (criteria.getCriteria().size() > 0) {
        logRecordExample.or().andUsernameLike(userName);
      }else{
        criteria.andUsernameLike(userName);
      }
    }

    if (email != null && !email.equals("")) {
      if (criteria.getCriteria().size() > 0) {
        logRecordExample.or().andEmailEqualTo(email);
      }else{
        criteria.andEmailEqualTo(email);
      }

    }

    PageHelper.startPage(current, size, true);

    PageInfo<LogRecord> pageInfo = new PageInfo<>(logRecordDao.selectByExample(logRecordExample));

    list =
        pageInfo.getList().stream().map(EntityToVOConverter::convert).collect(Collectors.toList());

    response.setRows(list);
    response.setCurrPage(current);
    response.setPageSize(size);
    response.setTotalPage(pageInfo.getPages());
    response.setTotal((int) pageInfo.getTotal());
    return response;
  }
}
